// 天气API请求
async function fetchWeather(city, type = '') {
  let url = 'api.php?city=' + encodeURIComponent(city);
  if (type) url += '&type=' + type;
  const res = await fetch(url);
  return await res.json();
}

function renderWeather(dataNow, data7d) {
  let html = '';
  // 实时天气卡片
  if (dataNow && dataNow.code === '200') {
    html += `<div class="card weather-card" style="max-width:400px;margin:24px auto 16px auto;padding:24px 28px 18px 28px;border-radius:18px;box-shadow:0 2px 16px #0001;background:linear-gradient(135deg,#e0e7ff 0%,#f8fafc 100%);">
      <div style="display:flex;align-items:center;justify-content:space-between;">
        <div style="display:flex;align-items:center;">
          <span style="font-size:48px;margin-right:16px;">${getWeatherIcon(dataNow.now.text || dataNow.now.weather || '')}</span>
          <div>
            <div style="font-size:22px;font-weight:bold;color:#222;">${dataNow.now.text || dataNow.now.weather || ''}</div>
            <div style="font-size:36px;font-weight:bold;color:#2563eb;line-height:1;">${dataNow.now.temp || dataNow.now.temperature || ''}<span style="font-size:20px;color:#888;">℃</span></div>
          </div>
        </div>
        <div style="text-align:right;min-width:90px;">
          <div style="font-size:14px;color:#888;">${dataNow.updateTime ? '更新时间：' + dataNow.updateTime : ''}</div>
        </div>
      </div>
      <div style="margin-top:18px;display:flex;flex-wrap:wrap;gap:12px 24px;font-size:16px;color:#444;">
        <div>体感温度：<b>${dataNow.now.feelsLike || ''}℃</b></div>
        <div>湿度：<b>${(dataNow.now.humidity || dataNow.now.sd || dataNow.now.SD) ? (dataNow.now.humidity || dataNow.now.sd || dataNow.now.SD) : '<span style="color:#e53e3e">暂无数据</span>'}</b></div>
        <div>风力：<b>${dataNow.now.windDir || ''} ${dataNow.now.windScale || ''}级</b></div>
        <div>气压：<b>${(dataNow.now.pressure || dataNow.now.qy) ? (dataNow.now.pressure || dataNow.now.qy) : '<span style="color:#e53e3e">暂无数据</span>'}</b></div>
      </div>
    </div>`;
  } else {
    html += '<div class="card weather-card">未查询到实时天气信息</div>';
  }
  // 未来7天天气卡片
  if (data7d && data7d.code === '200' && data7d.daily && data7d.daily.length > 0) {
    html += '<div class="card forecast-card" style="max-width:600px;margin:0 auto 24px auto;padding:18px 18px 10px 18px;border-radius:16px;box-shadow:0 2px 12px #0001;background:#f3f6fa;">';
    html += '<h3 style="margin:0 0 12px 0;font-size:20px;color:#2563eb;">未来天气</h3><div class="forecast7" style="display:flex;justify-content:space-between;gap:8px;">';
    // 只显示明天及以后的7天
    const todayStr = new Date().toISOString().slice(0,10);
    const futureDays = data7d.daily.filter(day => (day.fxDate || day.date) > todayStr).slice(0,7);
    futureDays.forEach(day => {
      // 获取星期
      const weekMap = ['日','一','二','三','四','五','六'];
      let weekStr = '';
      if(day.week) {
        weekStr = ' 星期' + (isNaN(day.week) ? day.week : weekMap[Number(day.week)%7]);
      } else if(day.fxDate || day.date) {
        const d = new Date(day.fxDate || day.date);
        weekStr = ' 星期' + weekMap[d.getDay()];
      }
      html += `<div class="day" style="flex:1 1 0;min-width:70px;background:#fff;border-radius:10px;padding:10px 6px;margin:0 2px;text-align:center;box-shadow:0 1px 4px #0001;">
        <div style="font-size:14px;color:#888;">${(day.fxDate || day.date || '') + weekStr}</div>
        <div style="font-size:22px;">${getWeatherIcon(day.textDay || day.dayweather || '')}</div>
        <div style="font-size:15px;font-weight:bold;color:#222;">${day.textDay || day.dayweather || ''}</div>
        <div style="font-size:13px;color:#888;">${day.textNight || day.nightweather || ''}</div>
        <div style="font-size:15px;color:#2563eb;margin:4px 0;">${(day.tempMin || day.nighttemp || '')}~${(day.tempMax || day.daytemp || '')}℃</div>
        <div style="font-size:12px;color:#888;">白:${day.daywind || day.windDirDay || ''}${day.daypower || day.windScaleDay || ''}级 夜:${day.nightwind || day.windDirNight || ''}${day.nightpower || day.windScaleNight || ''}级</div>
      </div>`;
    });
    html += '</div></div>';
  } else {
    html += '<div class="card forecast-card">未查询到未来七天天气信息</div>';
  }
  document.getElementById('weatherDisplay').innerHTML = html;
}

// 天气描述转emoji图标
function getWeatherIcon(desc) {
  if (!desc) return '🌈';
  if (desc.includes('雨')) return '🌧️';
  if (desc.includes('雪')) return '❄️';
  if (desc.includes('晴')) return '☀️';
  if (desc.includes('云')) return '⛅';
  if (desc.includes('阴')) return '☁️';
  if (desc.includes('雷')) return '⛈️';
  return '🌈';
}

document.getElementById('searchBtn').onclick = async function() {
  const city = document.getElementById('cityInput').value.trim();
  if (!city) return alert('请输入城市名');
  document.getElementById('weatherDisplay').innerHTML = '<div class="card">查询中...</div>';
  // 并发请求实时和7天
  const [dataNow, data7d] = await Promise.all([
    fetchWeather(city, 'now'),
    fetchWeather(city)
  ]);
  renderWeather(dataNow, data7d);
};

// 回车快捷查询
cityInput.addEventListener('keydown', function(e) {
  if (e.key === 'Enter') searchBtn.click();
});

// 自动定位并查询天气
window.addEventListener('DOMContentLoaded', function() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(async function(pos) {
      const lng = pos.coords.longitude;
      const lat = pos.coords.latitude;
      // 用高德逆地理API获取城市名
      const amapKey = await fetch('config.json').then(r=>r.json()).then(cfg=>cfg.amapKey || cfg.apiKey);
      const geoUrl = `https://restapi.amap.com/v3/geocode/regeo?location=${lng},${lat}&key=${amapKey}`;
      fetch(geoUrl)
        .then(res => res.json())
        .then(geo => {
          let city = '';
          if (geo.regeocode && geo.regeocode.addressComponent) {
            city = geo.regeocode.addressComponent.city;
            if (Array.isArray(city)) city = city[0];
            if (!city || city === '' || city === '[]') city = geo.regeocode.addressComponent.province;
          }
          if (city) {
            document.getElementById('cityInput').value = city;
            document.getElementById('searchBtn').click();
          } else {
            alert('定位成功，但未能识别到城市，请手动输入城市名');
          }
        })
        .catch(() => {
          alert('定位成功，但获取城市信息失败，请手动输入城市名');
        });
    }, function(err) {
      // 定位失败
      alert('定位失败，请手动输入城市名');
    });
  }
}); 